import { 
  Controller, 
  Get, 
  Post, 
  Put, 
  Delete, 
  Param, 
  Query, 
  Body, 
  UseGuards, 
  Request, 
  UseInterceptors, 
  UploadedFile,
  HttpCode,
  HttpStatus
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { GalleryService } from './gallery.service';
import { GalleryQueryDto } from './dto/gallery-query.dto';
import { UpdateGalleryImageDto } from './dto/update-gallery-image.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { diskStorage } from 'multer';
import { extname } from 'path';

@Controller('gallery')
@UseGuards(JwtAuthGuard)
export class GalleryController {
  constructor(private readonly galleryService: GalleryService) {}

  @Get('images')
  async findAll(@Query() query: GalleryQueryDto, @Request() req) {
    const data = await this.galleryService.findAll(query, req.user.id);
    return {
      code: 200,
      message: 'success',
      data,
      timestamp: Date.now(),
    };
  }

  @Get('images/:id')
  async findOne(@Param('id') id: string, @Request() req) {
    const data = await this.galleryService.findOne(+id, req.user.id);
    return {
      code: 200,
      message: 'success',
      data,
      timestamp: Date.now(),
    };
  }

  @Post('upload')
  @UseInterceptors(FileInterceptor('file', {
    storage: diskStorage({
      destination: './uploads',
      filename: (req, file, callback) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const ext = extname(file.originalname);
        const filename = `${uniqueSuffix}${ext}`;
        callback(null, filename);
      },
    }),
    fileFilter: (req, file, callback) => {
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'text/plain'];
      if (allowedTypes.includes(file.mimetype)) {
        callback(null, true);
      } else {
        callback(new Error('文件格式不支持'), false);
      }
    },
    limits: {
      fileSize: 10 * 1024 * 1024, // 10MB
    },
  }))
  async upload(
    @UploadedFile() file: Express.Multer.File,
    @Body('name') name: string,
    @Body('description') description: string,
    @Request() req
  ) {
    try {
      if (!file) {
        throw new Error('请选择要上传的文件');
      }

      console.log('Upload file:', file);
      console.log('Upload name:', name);
      console.log('Upload description:', description);
      console.log('Upload user:', req.user);

      const data = await this.galleryService.create(file, name, description, req.user.id);
      return {
        code: 200,
        message: '上传成功',
        data,
        timestamp: Date.now(),
      };
    } catch (error) {
      console.error('Upload error:', error);
      throw error;
    }
  }

  @Put('images/:id')
  async update(
    @Param('id') id: string,
    @Body() updateDto: UpdateGalleryImageDto,
    @Request() req
  ) {
    const data = await this.galleryService.update(+id, updateDto, req.user.id);
    return {
      code: 200,
      message: '更新成功',
      data,
      timestamp: Date.now(),
    };
  }

  @Delete('images/:id')
  @HttpCode(HttpStatus.OK)
  async remove(@Param('id') id: string, @Request() req) {
    await this.galleryService.remove(+id, req.user.id);
    return {
      code: 200,
      message: '删除成功',
      data: null,
      timestamp: Date.now(),
    };
  }
}
